// 引入公共配置
import { public_api } from '@/static/public.js';

/**
 * 获取用户ID（全局函数）
 * @returns {String} 用户ID
 */
function getUserId() {
  return uni.getStorageSync('uid') || '';
}

/**
 * 获取用户Token（全局函数）
 * @returns {String} 用户Token
 */
function getToken() {
  return uni.getStorageSync('token') || '';
}

/**
 * 请求封装函数
 * @param {Object} options 请求配置
 * @returns {Promise} 返回Promise对象
 */
function request(options) {
  return new Promise((resolve, reject) => {
    // 使用全局函数获取token和id
    const token = getToken();
    const id = getUserId();
    
    uni.request({
      url: options.url.startsWith('http') ? options.url : `${public_api}${options.url}`,
      method: options.method || 'POST',
      data: options.data || {},
      header: {
        'token': token,
        'id': id,
        ...options.header
      },
      success: (response) => {
        // 直接返回响应数据，让调用方处理
        resolve(response.data);
      },
      fail: (err) => {
        reject({
          code: -1,
          msg: '网络请求失败',
          data: err
        });
      }
    });
  });
}

// 首页相关接口
export const homeApi = {
  // 获取首页数据（包含轮播图、商品分类、热销商品列表）
  getHomeData: () => {
    return request({
      url: '/api',
      method: 'POST'
    });
  }
};

// 商品相关接口
export const productApi = {
  // 获取商品详情
  getProductDetail: (productId) => {
    return request({
      url: '/api/goods/detail',
      method: 'POST',
      data: {
        id: productId,
        uid: getUserId()
      }
    });
  },

  // 收藏商品
  collectProduct: (productId) => {
    return request({
      url: '/api/goods/star',
      method: 'POST',
      data: {
        id: productId,
        uid: getUserId()
      }
    });
  },

  // 取消收藏商品
  cancelCollectProduct: (productId) => {
    return request({
      url: '/api/goods/cancel_star',
      method: 'POST',
      data: {
        id: productId,
        uid: getUserId()
      }
    });
  },

  // 获取收藏列表
  getCollectList: () => {
    return request({
      url: '/api/goods/mystar',
      method: 'POST',
      data: {
        uid: getUserId()
      }
    });
  }
};

// 购物车相关接口
export const shoppingApi = {
  // 获取购物车列表
  getCartList: () => {
    return request({
      url: '/api/shopping',
      method: 'POST',
      data: {
        uid: getUserId()
      }
    });
  },
  
  // 加入购物车
  addToCart: (productId, num, norm) => {
    return request({
      url: '/api/shopping/add',
      method: 'POST',
      data: {
        uid: getUserId(),
        id: productId,
        num: num,
        norm: norm
      }
    });
  },

  // 更新购物车商品数量
  updateCartQuantity: (cartId, num) => {
    return request({
      url: '/api/shopping/update',
      method: 'POST',
      data: {
        id: String(cartId),
        num: String(num)
      }
    });
  },

  // 删除购物车商品
  deleteCartItem: (ids) => {
    // ids可以是单个id或逗号分隔的多个id
    const idStr = Array.isArray(ids) ? ids.join(',') : String(ids);
    return request({
      url: '/api/shopping/del',
      method: 'POST',
      data: {
        id: idStr,
        uid: getUserId()
      }
    });
  },

  // 购物车支付
  payFromCart: (shoppingIds, addressId) => {
    // shopping_ids 需要是 JSON 字符串格式
    const shoppingIdsStr = typeof shoppingIds === 'string' 
      ? shoppingIds 
      : JSON.stringify(shoppingIds);
    
    return request({
      url: '/api/shopping/pay',
      method: 'POST',
      data: {
        shopping_ids: shoppingIdsStr, // JSON字符串
        user_id: getUserId(),
        address_id:addressId
      }
    });
  }
};

// 订单相关接口
export const orderApi = {
  // 立即购买/支付订单
  payOrder: (addressId, goodsId, num, norm, money) => {
    return request({
      url: '/api/order/pay',
      method: 'POST',
      data: {
        user_id: getUserId(),
        address_id: addressId,
        goods_id: goodsId,
        num: String(num),
        norm: typeof norm === 'string' ? norm : JSON.stringify(norm),
        money: String(money)
      }
    });
  },

  // 订单列表
  // status: 1待付款 2待发货 3待收货 4待评价。不传或空为全部
  getOrderList: (status) => {
    const data = { user_id: getUserId() };
    if (status) data.status = String(status);
    return request({
      url: '/api/order',
      method: 'POST',
      data
    });
  }
};

// 分类相关接口
export const typeApi = {
  // 获取分类列表
  getTypeList: () => {
    return request({
      url: '/api/type',
      method: 'POST'
    });
  }
};

// 用户相关接口
export const userApi = {
  // 获取个人信息
  getUserCenter: () => {
    return request({
      url: '/api/user/center',
      method: 'POST',
      data: {
        uid: getUserId()
      }
    });
  },

  // 获取足迹列表
  getFootprint: () => {
    return request({
      url: '/api/user/spoor',
      method: 'POST',
      data: {
        uid: getUserId()
      }
    });
  }
};

// 收货地址相关接口
export const addressApi = {
  // 获取收货地址列表
  getAddressList: () => {
    return request({
      url: '/api/address',
      method: 'POST',
      data: {
        uid: getUserId()
      }
    });
  },

  // 保存/编辑收货地址
  saveAddress: (addressData) => {
    // addressData: { id?, name, tel, address, desc, default }
    const data = {
      uid: getUserId(),
      name: addressData.name,
      tel: addressData.tel,
      address: addressData.address,
      desc: addressData.desc,
      default: String(addressData.default || '0') // 1是默认地址，0不是
    };
    
    // 编辑时传递id
    if (addressData.id) {
      data.id = String(addressData.id);
    }
    
    return request({
      url: '/api/address/save',
      method: 'POST',
      data: data
    });
  },

  // 删除收货地址
  deleteAddress: (addressId) => {
    return request({
      url: '/api/address/del',
      method: 'POST',
      data: {
        id: String(addressId)
      }
    });
  }
};

